﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CoreData;
using ActionServices;
using Helper;
using System.Configuration;

namespace ZidoniCMS.Controllers
{
    public class PaymentController : BaseController
    {
        public PaymentController(IUserActionService _user, IOrderActionService _order,
            IOrderDetailActionService _orderdetail,
            IProductActionService _product, IEmailListActionService _emaillist,
            IEmailTemplateActionService _mailtemplate, IShoppingCartActionService _shoppingcart)
            : base(_user, _order, _orderdetail, _product, _emaillist, _mailtemplate, _shoppingcart)
        { }
        // GET: /Payment/

        public ActionResult Index()
        {
            List<ShoppingCart> model = (List<ShoppingCart>)Session["ShoppingCart"];
            if (model == null)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                return View(model);
            }
        }

        void ImportMail(int template, int orderid, string customername, string customeradd, string customerphone, string link, int total)
        {
            try
            {
                var userid = SessionManagement.GetSessionReturnInt("UserID");
                var email = EmailTemplateService.GetByID(2);
                var useremail = UserService.GetByID(userid);
                if (useremail != null)
                {
                    var lstnail = new EmailList();
                    lstnail.Email = useremail.Email;
                    lstnail.TitleExt = "Camera shop - Thông tin đơn hàng"; //String.Format("{0:0,0 vnđ}", price)
                    link = Helper.StringHelper.GetHost() + "/" + "order/detail/" + orderid;
                    lstnail.BodyExt = email.Template.Replace("{customername}", customername).Replace("{customeraddress}", customeradd).Replace("{link}", link).Replace("{customerphone}", customerphone);
                    string detail = Helper.EmailHelper.TableHeader() + GetDetailOrderMail() + Helper.EmailHelper.TableFooter(total);
                    lstnail.BodyExt = lstnail.BodyExt.Replace("{details}", detail);
                    MvcApplication.EmailQueue.Add(lstnail);
                }
            }
            catch { }
        }

        string GetDetailOrderMail()
        {
            string detail = "";// Helper.EmailHelper.TableHeader();
            ShoppingCart s = (ShoppingCart)Session["ShoppingCart"];
            var cartitem = ShoppingCartService.GetList();
            foreach (var item in cartitem)
            {
                detail += Helper.EmailHelper.TableOrderDetail(item.Product.Name, item.Amount, "10%", item.Product.Price);


            }
            return detail;
        }


        #region Pay

        public ActionResult PayAtStore()
        {
            int orderid = SessionManagement.GetSessionReturnInt("orderID");
            if (orderid == 0)
            {
                return RedirectToAction("Index", "Home");
            }
            var order = OrderService.GetByID(orderid);
            order.Status = (int)Helper.ValueDefine.OrderStatus.New;
            order.Note = "Khách hàng sẽ đến trực tiếp cửa hàng để thanh toán";
            OrderService.Save(order);
            ImportMail(2, orderid, order.Name, order.Address, order.Phone, "", order.TotalPrice);
            ClearCart();
            orderid = 0;
            return View();
        }

        public ActionResult PayDone(string PayerID, string Amount)
        {
            int orderid = SessionManagement.GetSessionReturnInt("orderID");
            var order = OrderService.GetByID(orderid);
            order.Status = (int)Helper.ValueDefine.OrderStatus.Paid;
            order.Note = "Khách hàng đã thanh toán thành công";
            OrderService.Save(order);
            ImportMail(2, orderid, order.Name, order.Address, order.Phone, "", order.TotalPrice);
            ClearCart();
            return View(order);
        }
        [HttpPost]
        public ActionResult PaymentAction(string address, string name, string phone, string email)
        {
           var userid = SessionManagement.GetSessionReturnInt("UserID");
           var orderid = SessionManagement.GetSessionReturnInt("orderID");
            List<ShoppingCart> model = (List<ShoppingCart>)Session["ShoppingCart"];
            //var host = "http://" + Request.Url.Host + ":" + Request.Url.Port;
            Order _order = new Order();
            _order.Active = true;
            _order.Address = address;
            _order.Name = name;
            _order.Note = "Đơn hàng mới, chưa được thanh toán";
            _order.Phone = phone;
            _order.CreateDate = DateTime.Now;
            _order.Ship_Fee = 0;
            _order.Email = email;

            var totalPrice = 0;
            foreach (var item in model) {
                totalPrice += item.TotalItemPrice;
            }
            _order.Status = (int)Helper.ValueDefine.OrderStatus.New;
            _order.TotalPrice = int.Parse(totalPrice.ToString());
            _order.UserID = userid;
            var id = OrderService.Save(_order);
            orderid = int.Parse(id.ToString());
            var Amount = 0;
            if (id > 0)
            {
                var cartitem = model;
                foreach (var item in cartitem)
                {
                    var _item = new OrderDetail();
                    _item.OrderID = id;
                    _item.Price = item.Product.Price;
                    _item.ProductID = item.Product.ID;
                    _item.Total = item.Product.Price * item.Amount;
                    _item.Amount = item.Amount;
                    OrderDetailService.Save(_item);
                    Amount += item.Amount;
                }
            }
            _order.ID = id;
            OrderService.Save(_order);
            return RedirectToAction("PayDone", "Payment", new { PayerID = orderid, Amount = Amount });
        }
        #endregion


        #region Other

        [HttpPost]
        public ActionResult GetInfo()
        {
            try
            {
                var userid = SessionManagement.GetSessionReturnInt("UserID");
                var data = UserService.GetByID(userid);
                return Json(data, JsonRequestBehavior.AllowGet);
            }
            catch { return Content(""); }
        }


        void ClearCart()
        {
            List<ShoppingCart> model = (List<ShoppingCart>)Session["ShoppingCart"];
            model.Clear();
            Session["ShoppingCart"] = model;
        }

        void UpdateProductSole()
        {
            List<ShoppingCart> model = (List<ShoppingCart>)Session["ShoppingCart"];
            foreach (var item in model)
            {
                ProductService.UpdateSoleAmount(int.Parse(item.Product.ID.ToString()), item.Amount);
            }
        }

        #endregion
    }
}
